package top.xphu.aliyun.orc;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.api.util.HttpUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import top.xphu.aliyun.orc.entity.Message;
import top.xphu.aliyun.orc.entity.OrcConfig;
import top.xphu.aliyun.orc.entity.OrcResponseBody;
import top.xphu.aliyun.orc.entity.Query;
import top.xphu.aliyun.orc.enums.StatusCode;
import top.xphu.aliyun.orc.exception.ImgNullException;

import java.util.HashMap;
import java.util.Map;

/**
 * ORC图片识别操作类
 * @author xphu
 * @version 1.0
 * @date 2021/9/6 17:23
 */
public class OrcTools {
    private final OrcCore orcCore;

    public OrcTools(OrcCore orcCore) {
        this.orcCore = orcCore;
    }

    /**
     * 发送请求
     * @param url,fileBase64
     * @return
     */
    public String sendPleaToJson(String url){
        try {
            HttpEntity httpEntity = doPost(url);
            String responseBody = null;
            if (httpEntity != null) {
                responseBody = EntityUtils.toString(httpEntity,"UTF-8");
            }
            return responseBody;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Map<String, Object> sendPleaToMap(String url){
        try {
            HttpEntity httpEntity = doPost(url);
            String responseBody = null;
            if (httpEntity != null) {
                responseBody = EntityUtils.toString(httpEntity,"UTF-8");
            }
            return JSONObject.parseObject(responseBody, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Message sendPleaToMessage(String url){
        try {
            HttpEntity httpEntity = doPost(url);
            String responseBody = null;
            if (httpEntity != null) {
                responseBody = EntityUtils.toString(httpEntity,"UTF-8");
            }
            return JSONObject.parseObject(responseBody, Message.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private Map<String, String> getHeaders(String appcode){
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        return headers;
    }

    /**
     * 获取请求体
     * @param image 图片连接、Base64
     * @param config 配置文件
     * @return jsonStr
     */
    public String getBody(String image, OrcConfig config){
        return JSONObject.toJSONString(new OrcResponseBody(image, config));
    }

    private HttpEntity doPost(String url) throws Exception {
        if (StringUtils.isEmpty(url)){
            throw new ImgNullException(StatusCode.IMG_UNDEFIND.msg);
        }
        // 获取请求头
        Map<String, String> headers = getHeaders(orcCore.getProperties().getAppcode());

        HashMap<String, Object> config = new HashMap<String, Object>();
        OrcConfig orcConfig = new OrcConfig();
        orcConfig.setFormat("json");
        orcConfig.setFinance(false);
        orcConfig.setDir_assure(false);

        String body = getBody(url, orcConfig);

        HttpResponse response = HttpUtils.doPost(OrcProperties.getHost(), OrcProperties.getPath(), OrcProperties.getMethod(), headers, Query.build(), body);
        // 校验请求状态码
        checkStatusCode(response.getStatusLine().getStatusCode());
        return response.getEntity();
    }

    /**
     * 校验请求状态码
     * @param code 状态码 200：成功 462：图片不存在
     */
    private void checkStatusCode (int code){
        if (code == StatusCode.SUCCESS.code){
            return;
        } else if (code == StatusCode.IMG_UNDEFIND.code){
            throw new ImgNullException(StatusCode.IMG_UNDEFIND.msg);
        } else {
            throw new RuntimeException("未知异常");
        }
    }
}
